package com.crowntit.infrastructure.redis;

import org.redisson.api.RBitSet;
import org.redisson.api.RLock;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;

public interface IRedisService {
    RBitSet getBitSet(String key);

    default int getIndexFromUserId(String userId) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] hashBytes = md.digest(userId.getBytes(StandardCharsets.UTF_8));
            // 将哈希字节数组转换为正整数
            BigInteger bigInt = new BigInteger(1, hashBytes);
            // 取模以确保索引在合理范围内
            return bigInt.mod(BigInteger.valueOf(Integer.MAX_VALUE)).intValue();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 algorithm not found", e);
        }
    }

    RLock getLock(String key);

    void setAtomicLong(String key, long value);

    Long getAtomicLong(String key);

    long incr(String key);

    Boolean setNx(String key, long exprired, TimeUnit timeUnit);

    <T> T getValue(String key);

    <T> void setValue(String key, T value);

    <T> void setValue(String key, T value, long expired);
}
